package com.mdchuxing.user.database

import android.content.Context
import com.tanguy.user.bean.PeopleModel
import com.tanguy.user.db.MyDatabaseOpenHelper
import org.jetbrains.anko.db.*

/**
 * Created by zhangyujiu on 2017/8/9.
 */
object ContactHistoryManager {
    /**
     * 判断表中是否含有相同数据
     */
    fun isHasSameData(context: Context, phone: String): Boolean {
        val database = MyDatabaseOpenHelper.getInstance(context)
        val db = database.readableDatabase
        val rowParser = classParser<PeopleModel>()
        val data = db.select("Contact").whereArgs("phone={phone}", "phone" to phone).parseList(rowParser)
        return data.isNotEmpty()
    }

    /**
     * 保存联系人信息
     */
    fun saveContact(context: Context, name:String,phone:String) {
        val database = MyDatabaseOpenHelper.getInstance(context)
        val db = database.writableDatabase
        db.insert("Contact",
                "name" to name,
                "phone" to phone)
    }

    /**
     * 加载本地数据
     */
    fun getPeoples(context: Context): List<PeopleModel> {
        val database = MyDatabaseOpenHelper.getInstance(context)
        val db = database.readableDatabase
        val rowParser = classParser<PeopleModel>()
        val data = db.select("Contact").orderBy("id", SqlOrderDirection.DESC).parseList(rowParser)
        return data
    }

    /**
     * 清空数据
     */
    fun clearTable(context: Context){
        val database = MyDatabaseOpenHelper.getInstance(context)
        val db = database.readableDatabase
        db.delete("Contact")
    }
}